import { getInfo } from "@/api/user";
import { login, logout } from "@/api/login";
import { defineStore } from "pinia";

const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    name: '',
    account:''
  }),
  persist: {
    storage: localStorage,
    paths: ['token','name']
  },
  actions: {
    // 用户登录
    login(userInfo: { account: string, password: string }) {
      const { account, password, uniqid, code } = userInfo
      return new Promise((resolve, reject) => {
				let data = {
					account,
					password,
					uniqid,
					code
				}
        login(data).then(res => {
					if(res.state == 200){
						this.token = res.data
						// localStorage.setItem('ADMIN_PAI_TOKEN', res.data)
					}
					resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
					if(res.state == 200){
						const { data } = res
            this.account = data.account
            localStorage.setItem('ACCOUNT', this.account)
						this.name = data
						resolve(res)
					}else{
						if (!data) return reject('验证失败，请重新登录')
						resolve({})
					}
          
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 登出
    logout() {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          this.resetToken()
          resolve({})
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 清除登录态
    resetToken() {
			console.log('清空')
			// localStorage.removeItem('ADMIN_PAI_TOKEN')
      this.token = ''
      this.name = ''
    }
  }
})

export default useUserStore
